package com.android.lpiquiz;

import com.android.lpiquiz.data.TestQuestion;
import com.android.lpiquiz.data.QuizXmlParser;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class LPIQuizActivity extends Activity
{
    Button previousButton;
    Button nextButton;
    LPIQuizModel lpiQuizModel;
    TextView testQuestion;
    TextView testExplenation;
    CheckBox answersCheckBox [];
    RadioButton answersRadioButton [];
    RadioGroup radioGroupSing;
    RadioGroup radioGroupMult;
    
    QuizXmlParser quizXmlParser;
    boolean isCheckMode;
    boolean wronAnswersOnly;
	
    public LPIQuizActivity()
    {
		lpiQuizModel=new LPIQuizModel();
		answersCheckBox = new CheckBox [TestQuestion.MAX_ANSWERS];
		answersRadioButton = new RadioButton [TestQuestion.MAX_ANSWERS];
		isCheckMode=false;
		wronAnswersOnly=false;
    }
    
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.testquestion);
		testQuestion = (TextView)findViewById(R.id.QuestionTextView);
		testExplenation = (TextView)findViewById(R.id.ExplenationTextView);
		testExplenation.setVisibility(View.GONE);
		radioGroupMult = (RadioGroup)findViewById(R.id.RadioGroupMult);
		radioGroupSing = (RadioGroup)findViewById(R.id.RadioGroupSing);
        previousButton = (Button)findViewById(R.id.PreviousSing);
        nextButton = (Button)findViewById(R.id.NextSing);
        
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String lpicExameType = preferences.getString("list_lpic_exame", "101");
        wronAnswersOnly = preferences.getBoolean("wrong_answers_only", false);
        
		quizXmlParser = new QuizXmlParser();
		quizXmlParser.getData(getApplicationContext(),lpicExameType);
		lpiQuizModel.setTestQuestions(quizXmlParser.getRandomTestQuestions());
        
    	if (lpiQuizModel.isMultipleChoice())
    	{
    		setMultipleChoiceView();
    	}
    	else
    	{
    		setSingleChoiceView();
    	}
        
        previousButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
            	setUserAnswers();
            	if (isCheckMode && wronAnswersOnly==true)
            	{
            		lpiQuizModel.setPreviousWrong();
            	}
            	else
            	{
            		lpiQuizModel.setPrevious();
            	}
            	if (lpiQuizModel.isMultipleChoice())
            	{
            		setMultipleChoiceView();
            	}
            	else
            	{
            		setSingleChoiceView();
            	}
            	if (isCheckMode)
            	{
            		testExplenation.setText(lpiQuizModel.getExplanation());
            	}
            	nextButton.setText(R.string.next);
            }
        });
        
        nextButton.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View view)
            {
            	if (lpiQuizModel.getIterator()<LPIQuizModel.MAX_TEST_QUESTIONS-1)
            	{
            		setUserAnswers();
                	if (isCheckMode && wronAnswersOnly==true)
                	{
                		lpiQuizModel.setNextWrong();
                		/*
                		if (lpiQuizModel.getIterator()==lpiQuizModel.getWrongAnswersIndexList().size()-1)
                		{
                			nextButton.setText(R.string.finish);
                		}
                		*/
                	}
                	else
                	{
                		lpiQuizModel.setNext();
            		}
            		if (lpiQuizModel.getIterator()==LPIQuizModel.MAX_TEST_QUESTIONS-1)
            		{
            			nextButton.setText(R.string.finish);
            		}
	            	if (lpiQuizModel.isMultipleChoice())
	            	{
	            		setMultipleChoiceView();
	            	}
	            	else
	            	{
	            		setSingleChoiceView();
	            	}
	            	if (isCheckMode)
	            	{
	            		testExplenation.setText(lpiQuizModel.getExplanation());
	            	}
            	}
            	else
            	{
            		setUserAnswers();
        			lpiQuizModel.checkAnswers();
        			int numberOfWrongAnswers = lpiQuizModel.getWrongAnswersIndexList().size();
        			double result=(double)(LPIQuizModel.MAX_TEST_QUESTIONS-numberOfWrongAnswers)/(double)LPIQuizModel.MAX_TEST_QUESTIONS;
        			new AlertDialog.Builder(view.getContext())
        			.setTitle("Quiz is finished")
        			.setMessage("Result: "+(int)(result*100)+"%\n"+"Wrong answers: "+numberOfWrongAnswers+"\nRight answers: "+(LPIQuizModel.MAX_TEST_QUESTIONS-numberOfWrongAnswers))
        			.setPositiveButton("Review answers", new DialogInterface.OnClickListener()
        			{
        				public void onClick(DialogInterface dialog, int whichButton)
        				{
                			if (wronAnswersOnly==true && lpiQuizModel.getWrongAnswersIndexList().size()>0)
                			{
                				lpiQuizModel.setFirstWrong();
                			}
                			else
                			{
            					lpiQuizModel.setFirst();
                			}
        					
                			isCheckMode=true;
                			testExplenation.setText(lpiQuizModel.getExplanation());
                			testExplenation.setVisibility(View.VISIBLE);
                			nextButton.setText(R.string.next);
                			setRigtAnswers();
                			setNotEditable();
                			
                        	if (lpiQuizModel.isMultipleChoice())
                        	{
                        		setMultipleChoiceView();
                        	}
                        	else
                        	{
                        		setSingleChoiceView();
                        	}
        				}
        			})
        			.setNegativeButton("Finish Quiz", new DialogInterface.OnClickListener()
        			{
        				public void onClick(DialogInterface dialog, int whichButton)
        				{
                            Intent intent = new Intent();
                            setResult(RESULT_OK, intent);
                            finish();
        				}
        			})
        			.show();
            	}
            }
        });
    }
	
    private void setRigtAnswers()
    {
    	if (lpiQuizModel.isMultipleChoice())
    	{
			for (int i=0; i<TestQuestion.MAX_ANSWERS; i++)
			{
				if (lpiQuizModel.isCorrectAnswer(i))
				{
					answersCheckBox[i].setTextColor(android.graphics.Color.RED);
				}
				else
				{
					answersCheckBox[i].setTextColor(android.graphics.Color.WHITE);
				}
			}
    	}
    	else
    	{
			for (int i=0; i<TestQuestion.MAX_ANSWERS; i++)
			{
				if (lpiQuizModel.isCorrectAnswer(i))
				{
					answersRadioButton[i].setTextColor(android.graphics.Color.RED);
				}
				else
				{
					answersRadioButton[i].setTextColor(android.graphics.Color.WHITE);
				}
			}
    	}
    }
    
    private void setNotEditable()
    {
    	for (int i=0; i<TestQuestion.MAX_ANSWERS; i++)
    	{
    		answersRadioButton[i].setEnabled(false);
    		answersCheckBox[i].setEnabled(false);
    	}
    }
    
    private void setSingleChoiceView()
    {
    	testQuestion.setText(Html.fromHtml((lpiQuizModel.getIterator()+1)+". "+lpiQuizModel.getQuestion()));
    	radioGroupSing = (RadioGroup)findViewById(R.id.RadioGroupSing);
    	radioGroupMult.setVisibility(View.GONE);
		radioGroupSing.setVisibility(View.VISIBLE);
		answersRadioButton[0] = (RadioButton)findViewById(R.id.AnswerARadioButton);
		answersRadioButton[1] = (RadioButton)findViewById(R.id.AnswerBRadioButton);
		answersRadioButton[2] = (RadioButton)findViewById(R.id.AnswerCRadioButton);
		answersRadioButton[3] = (RadioButton)findViewById(R.id.AnswerDRadioButton);
		radioGroupSing.clearCheck();
		
		for (int i=0; i<TestQuestion.MAX_ANSWERS; i++)
		{
			answersRadioButton[i].setText(lpiQuizModel.getAnswerName(i) +") "+lpiQuizModel.getAnswer(i));
		}
		
		for (int i=0; i<TestQuestion.MAX_ANSWERS; i++)
		{
			if (lpiQuizModel.getUserAnswer(i)==true)
			{
				answersRadioButton[i].setChecked(true);
				break;
			}
			else
			{
				answersRadioButton[i].setChecked(false);
			}
		}
		
		if (isCheckMode)
		{
			setRigtAnswers();
		}
    }
    
    private void setMultipleChoiceView()
    {
    	testQuestion.setText(Html.fromHtml((lpiQuizModel.getIterator()+1)+". "+lpiQuizModel.getQuestion()));
    	radioGroupMult = (RadioGroup)findViewById(R.id.RadioGroupMult);
    	radioGroupSing.setVisibility(View.GONE);
		radioGroupMult.setVisibility(View.VISIBLE);
		answersCheckBox[0] = (CheckBox)findViewById(R.id.AnswerACheckBox);
		answersCheckBox[1] = (CheckBox)findViewById(R.id.AnswerBCheckBox);
		answersCheckBox[2] = (CheckBox)findViewById(R.id.AnswerCCheckBox);
		answersCheckBox[3] = (CheckBox)findViewById(R.id.AnswerDCheckBox);
		radioGroupMult.clearCheck();
		
		for (int i=0; i<TestQuestion.MAX_ANSWERS; i++)
		{
			answersCheckBox[i].setText(lpiQuizModel.getAnswerName(i) +") "+lpiQuizModel.getAnswer(i));
			if (lpiQuizModel.getUserAnswer(i)==true)
			{
				answersCheckBox[i].setChecked(true);
			}
			else
			{
				answersCheckBox[i].setChecked(false);
			}
		}
		
		if (isCheckMode)
		{
			setRigtAnswers();
		}
    }
    
    private void setUserAnswers()
    {
    	if (lpiQuizModel.isMultipleChoice())
    	{
	    	for (int i=0; i<TestQuestion.MAX_ANSWERS; i++)
	    	{
	    		lpiQuizModel.setUserAnswer(i, answersCheckBox[i].isChecked());
	    	}
    	}
    	else
    	{
	    	for (int i=0; i<TestQuestion.MAX_ANSWERS; i++)
	    	{
	    		lpiQuizModel.setUserAnswer(i, answersRadioButton[i].isChecked());
	    	}
    	}
    }
    
}
